package com.rfid.assistant.activity.presenter;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import com.rfid.assistant.App;
import com.rfid.assistant.BluetoothManager;
import com.rfid.assistant.activity.view.IMainView;
import com.rfid.assistant.bean.DaoSession;
import com.rfid.assistant.bean.Machine;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MainPresenter {

    IMainView mView;
    private Executor mExecutor = Executors.newSingleThreadExecutor();
    private Handler mHandler = new Handler();

    public MainPresenter(IMainView view) {
        mView = view;
    }

    public void connectAndAddMachine(final String mac) {
        System.out.println("connectAndAddMachine mac = " + mac);
        mView.showConnecting();
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BluetoothManager.INSTANCE.connect(mac);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            BluetoothDevice device = BluetoothManager.INSTANCE.getDevice(mac);
                            mView.onConnect(device.getName(),device.getAddress());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mView.onConnectFail();
                        }
                    });
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mView.hideConnecting();
                    }
                });
            }
        });
    }

    public void saveDoor(Machine machine) {
        DaoSession daoSession = App.getInstance().getDaoSession();
        daoSession.getMachineDao().save(machine);
    }

    public List<Machine> getMachines() {
        DaoSession daoSession = App.getInstance().getDaoSession();
        return daoSession.getMachineDao().queryBuilder().list();
    }

    public void updateMachine(Machine machine) {
        DaoSession daoSession = App.getInstance().getDaoSession();
        daoSession.getMachineDao().update(machine);
    }

    public void deleteMachine(Machine machine) {
        DaoSession daoSession = App.getInstance().getDaoSession();
        daoSession.getMachineDao().delete(machine);
    }
}
